package com.lanou.fooddemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.lanou.fooddemo.R;
import com.lanou.fooddemo.activity.TopicDetailsActivity;
import com.lanou.fooddemo.adapter.TopicAdapter;
import com.lanou.fooddemo.bean.DataBean;
import com.lanou.fooddemo.bean.DetailBean;
import com.lanou.fooddemo.external.material_loading_progress_bar.CircleProgressBar;
import com.lanou.fooddemo.external.smart_image_view.SmartImageView;
import com.lanou.fooddemo.external.swipe_refresh_loading_layout.SwipeRefreshLoadingLayout;
import com.lanou.fooddemo.theme.FoodTheme;
import com.lanou.fooddemo.util.CommonUtil;
import com.lanou.fooddemo.util.NetUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dlios on 15-8-3.
 */
public class TopicsFragment extends Fragment {

    private static final String LOG_TAG = "TopicActivity";//打印信息

    public static final String TOPICDETAILS_KEY = "topicDetails";
    private final int TYPE_DIOLOG_SHOW = 1;  //设置读取中dialog显示类型值
    private final int TYPE_GET_DATA = 2;  // 首次拉取数据的Message的类型值
    private final int TYPE_GET_NEXT_DATA = 3;   //非首次拉取数据的Message的类型值


    private List<DataBean> dataBeans;
    private TopicAdapter adapter;


    //定义list刷新进度条颜色
    private int[] listColor = {android.R.color.holo_red_light, android.R.color.white,
            android.R.color.holo_red_light, android.R.color.holo_red_light};
    private Handler handler;

    private ListView listView;  //数据ListView
    private SwipeRefreshLoadingLayout swipeRefreshLoadingLayout;   //刷新布局
    private CircleProgressBar circleProgressBar;   //读取中Dialog
    private SmartImageView recommendedTopicsLeftImageView;
    private SmartImageView recommendeTopicsRightImageView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //通过LayoutInflater从layout布局中获得布局view
        View view = inflater.inflate(R.layout.topics_listview, null);

//        //初始化控件
//        @ViewInject(id = R.id.button, click = "onClick")
//        Button button;
//        @ViewInject(id = R.id.RecommendedTopicsLeftImageView)
//        SmartImageView recommendedTopicsLeftImageView;
//        @ViewInject(id = R.id.RecommendeTopicsRightImageView)
//        SmartImageView recommendeTopicsRightImageView;
//        @ViewInject(id = R.id.textView)
//        TextView textView;
//        @ViewInject(id = R.id.recommendedTopicsListview)
//        AutoListView recommendedTopicsListview;

        initView(view);   //初始化控件
        getSameCityData(TYPE_GET_DATA);


        return view;
    }


    //控件初始化方法     @param view 布局View
    private void initView(View view) {
        listView = (ListView) view.findViewById(R.id.topicsListview);
        swipeRefreshLoadingLayout =
                (SwipeRefreshLoadingLayout) view.findViewById(R.id.topicSwipeLayout);
        circleProgressBar = (CircleProgressBar) view.findViewById(R.id.topicProgressBar);

        circleProgressBar.setVisibility(View.VISIBLE); //设置读取中dialog显示
        dataBeans = new ArrayList<DataBean>(); //初始化列表数据
        adapter = new TopicAdapter(getActivity(), dataBeans);  //初始化列表适配器
        //为listView绑定适配器
        listView.setAdapter(adapter);


        //为刷新布局添加进度条颜色
        swipeRefreshLoadingLayout.setColor(listColor[0], listColor[1],
                listColor[2], listColor[3]);
        //注册下拉刷新
        swipeRefreshLoadingLayout.setOnRefreshListener(new SwipeRefreshLoadingLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取首次拉取数据
                getSameCityData(TYPE_GET_DATA);
            }
        });
        //注册上拉加载更多
        swipeRefreshLoadingLayout.setOnLoadListener(new SwipeRefreshLoadingLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                //加载更多数据
                getSameCityData(TYPE_GET_NEXT_DATA);
            }
        });

        //注册listView按下监听
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //创建跳转详细信息界面的Activity的Intent
                Intent intent = new Intent(getActivity(), TopicDetailsActivity.class);
                //获取列表相应点击位置的跳转信息
                DetailBean detailBean;
                if (position == 0) {

                } else {
                    detailBean = dataBeans.get(position + 1).getDetail();
                    //将需要跳转的url携带信息传递到详细信息界面
                    intent.putExtra(TOPICDETAILS_KEY, detailBean.getApi());
                    //跳转到详细信息界面
                    startActivity(intent);
                }

            }

        });


        handler = new Handler(new Handler.Callback() {


            @Override
            public boolean handleMessage(Message msg) {   //
                switch (msg.what) {
                    case TYPE_DIOLOG_SHOW:

                        circleProgressBar.setVisibility(View.VISIBLE);

                        break;


                    case TYPE_GET_DATA: //处理首次进入和下拉刷新的数据更新
                        dataBeans.clear(); //清空dataBeans的List
                        dataBeans.addAll((List<DataBean>) msg.obj); //将msg中的数据全部填充到dataBeans
                        //取消刷新状态
                        swipeRefreshLoadingLayout.setRefreshing(false);
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;

                    case TYPE_GET_NEXT_DATA:   //处理加载更多的数据更新
                        dataBeans.addAll((List<DataBean>) msg.obj);//将msg中的数据全部填充到dataBeans
                        swipeRefreshLoadingLayout.setLoading(false);//取消加载更多状态
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;
                }
                //通知适配器数据改变，更新视图
                adapter.notifyDataSetChanged();
                return true;
            }
        });
        //设置主题
        setTheme();
    }

    @Override
    public void onResume() {
        super.onResume();
        //设置主题
        setTheme();
    }

    /**
     * 获取数据
     * //@param url 获取数据的url
     *
     * @param type 拉取类型，是刷新或首次拉取还是非首次拉取
     */
    private void getSameCityData(int type) {
        //实例化自定义Runable接口类SameCityRunable
        SameCityRunable sameCityRunable = new SameCityRunable(type);
        //将Runable实例类放入Thread构造方法,实例化线程
        Thread thread = new Thread(sameCityRunable);
        //开启线程
        thread.start();
    }

    private class SameCityRunable implements Runnable {

        /**
         * 读取中进度条显示消息
         */
        private Message msgDialogShow;
        /**
         * 数据传递消息
         */
        private Message msgData;
        /**
         * 首次拉取或非首次拉取类型
         */
        private int type;
        List<DataBean> runableDataBeanList = null;

        public SameCityRunable(int t) {
            type = t;
        }

        @Override
        public void run() {
            //从handler中获取消息赋给进度条显示消息
            msgDialogShow = handler.obtainMessage();
            //设置消息类型what值
            msgDialogShow.what = TYPE_DIOLOG_SHOW;
            //发送进度条显示消息
            handler.sendMessage(msgDialogShow);
            //判断数据拉取类型，从不同接口拉取数据
            if (TYPE_GET_DATA == type) {
                runableDataBeanList = NetUtil.getDataBeanListDataForTopicList();
            } else if (TYPE_GET_NEXT_DATA == type) {

                runableDataBeanList = NetUtil.getDataBeanListDataForTopicListForNext();
                Log.i("liuyan", "next data " + runableDataBeanList.get(2).getTitle());
            }

            if (CommonUtil.isListNotNull(runableDataBeanList)) {
                //从handler获取消息
                msgData = handler.obtainMessage();
                //设置消息what值
                msgData.what = type;
                //设置消息obj内容值
                msgData.obj = runableDataBeanList;
                //发送消息给handler
                handler.sendMessage(msgData);
            }
        }
    }
    /**
     * 设置主题
     */
    public void setTheme() {
        listColor[0] = FoodTheme.getLoadingLayoutProcessColor();
        listColor[2] = FoodTheme.getLoadingLayoutProcessColor();
        listColor[3] = FoodTheme.getLoadingLayoutProcessColor();
        swipeRefreshLoadingLayout.setColor(listColor[0], listColor[1],
                listColor[2], listColor[3]);
        circleProgressBar.setColorSchemeResources(new int[]{FoodTheme.getCircleProgressBarColor()});
    }
}




